//
//  DSRefreshFooterView.m
//  zzzz
//
//  Created by rainday on 15/1/24.
//  Copyright (c) 2015年 rainday. All rights reserved.
//

#import "DSLoadFooterView.h"


#define TEXT_COLOR	 [UIColor colorWithRed:87.0/255.0 green:108.0/255.0 blue:137.0/255.0 alpha:1.0]
#define FLIP_ANIMATION_DURATION 0.18f

@interface DSLoadFooterView()

- (void)setState:(DSLoadFooterViewState)aState;
@end


@implementation DSLoadFooterView

- (id)initWithFrame:(CGRect)frame{

    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor clearColor];
        _statusLabel = [[UILabel alloc] initWithFrame:CGRectMake(0.0f, 30, self.frame.size.width, 20.0f)];
        _statusLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
        _statusLabel.font = [UIFont boldSystemFontOfSize:13.0f];
        _statusLabel.textColor = TEXT_COLOR;
        _statusLabel.shadowColor = [UIColor colorWithWhite:0.9f alpha:1.0f];
        _statusLabel.shadowOffset = CGSizeMake(0.0f, 1.0f);
        _statusLabel.backgroundColor = [UIColor clearColor];
        _statusLabel.textAlignment = NSTextAlignmentCenter;
        [self addSubview:_statusLabel];
        
        
        _arrowImage = [CALayer layer];
        _arrowImage.frame = CGRectMake(25.0f, 10, 30.0f, 55.0f);
        _arrowImage.contentsGravity = kCAGravityResizeAspect;
        _arrowImage.contents = (id)[UIImage imageNamed:@"blackArrow.png"].CGImage;
        
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 40000
        if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)]) {
            _arrowImage.contentsScale = [[UIScreen mainScreen] scale];
        }
#endif
        
        [[self layer] addSublayer:_arrowImage];
        
        
        _activityView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
        _activityView.frame = CGRectMake(25.0f, 25, 20.0f, 20.0f);
        [self addSubview:_activityView];

        [self setState:DSLoadFooterViewStateNormal];
    }
    return self;
}

#pragma mark setter

- (void)setState:(DSLoadFooterViewState)aState{
    switch (aState) {
        case DSLoadFooterViewStateNormal:
            if (_state == DSLoadFooterViewStateLoading) {
                [CATransaction begin];
                [CATransaction setAnimationDuration:FLIP_ANIMATION_DURATION];
                _arrowImage.transform = CATransform3DIdentity;
                [CATransaction commit];
                
            }
            
            _statusLabel.text = NSLocalizedString(@"上拉加载更多", @"上拉加载更多");
            [_activityView stopAnimating];
            [CATransaction begin];
            [CATransaction setValue:(id)kCFBooleanTrue forKey:kCATransactionDisableActions];
            _arrowImage.hidden = NO;
            _arrowImage.transform = CATransform3DIdentity;
            [CATransaction commit];
            
            
            break;
        case DSLoadFooterViewStateLoading:
            _statusLabel.text = NSLocalizedString(@"正在加载...", @"正在加载...");
            [_activityView startAnimating];
            [CATransaction begin];
            [CATransaction setValue:(id)kCFBooleanTrue forKey:kCATransactionDisableActions];
            _arrowImage.hidden = YES;
            [CATransaction commit];
            break;
        case DSLoadFooterViewStatePulling:
            _statusLabel.text = NSLocalizedString(@"松开加载数据", @"松开加载数据");
            [CATransaction begin];
            [CATransaction setAnimationDuration:FLIP_ANIMATION_DURATION];
            _arrowImage.transform = CATransform3DMakeRotation((M_PI/180.0)*180.0f, 0.0, 0.0, 1.0);
            [CATransaction commit];
            
            
            break;
        default:
            break;
    }
    
    _state = aState;
    
}


#pragma mark ScrollView Methods

- (void)dsLoadScrollViewDidScroll:(UIScrollView *)scrollView{
    
    CGFloat pullY = scrollView.contentOffset.y-(scrollView.contentSize.height-scrollView.frame.size.height);
    if (pullY < 0 || scrollView.contentOffset.y < 0) {
        
        self.hidden = YES;
        return;
    }
    self.hidden = NO;
    [self setFrame:CGRectMake(0, MAX(scrollView.contentSize.height, scrollView.frame.size.height), scrollView.frame.size.width, 60)];
   
    
    if (_state == DSLoadFooterViewStateLoading) {
        
        CGFloat offset = MIN(pullY, 60);
        scrollView.contentInset = UIEdgeInsetsMake(0, 0, offset, 0);
        
    }else if (scrollView.isDragging){
        BOOL _isLoading = NO;
        if ([_delegate respondsToSelector:@selector(dsLoadTableViewIsLoading:)]) {
            _isLoading = [_delegate dsLoadTableViewIsLoading:self];
        }
        
        if (_state == DSLoadFooterViewStatePulling && pullY <60 && !_isLoading) {
            [self setState:DSLoadFooterViewStateNormal];
        }else if(_state == DSLoadFooterViewStateNormal && pullY>60 && !_isLoading){
            [self setState:DSLoadFooterViewStatePulling];
        }
        
        if (scrollView.contentInset.top !=0 ) {
            scrollView.contentInset = UIEdgeInsetsZero;
            
        }
        
        
    }
    
}

- (void)dsLoadScrollViewDidEndDragging:(UIScrollView *)scrollView{
    
    CGFloat pullY = scrollView.contentOffset.y-(scrollView.contentSize.height-scrollView.frame.size.height);
    if (pullY<0  || scrollView.contentOffset.y < 0) {
        self.hidden = YES;
        return;
    }
    
    
    BOOL _loading = NO;
    if ([_delegate respondsToSelector:@selector(dsLoadTableViewIsLoading:)]) {
        _loading = [_delegate dsLoadTableViewIsLoading:self  ];
    }
    
    if (pullY > 60 && !_loading) {
        
        if ([_delegate respondsToSelector:@selector(dsLoadTableViewDidTriggedLoad:)]) {
            [_delegate dsLoadTableViewDidTriggedLoad :self];
        }
        
        [self setState:DSLoadFooterViewStateLoading];
        [UIView beginAnimations:nil context:NULL];
        [UIView setAnimationDuration:0.2];
        scrollView.contentInset = UIEdgeInsetsMake(0, 0, 60, 0);
        [UIView commitAnimations];
        
    }
}


- (void)dsLoadScrollViewDataSourceDidFinishedLoading:(UIScrollView *)scrollView{
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:.3];
    [scrollView setContentInset:UIEdgeInsetsMake(0.0f, 0.0f, 0.0f, 0.0f)];
    [UIView commitAnimations];
    
    [self setState:DSLoadFooterViewStateNormal];
    self.hidden = YES;
    
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
